#include <iostream>
using namespace std;

void draw(int n)
{
    int array[100][100];
    
    int dmode = 0; // 0:right 1:bot 2:left 3:top
    int count = 4;
    int cnc = n-1;
    int nc = 0;
    int value = 1;
    
    for(int x=0, y=0;value != n*n+1;)
    {   
        array[x][y] = value++;

        switch(dmode)
        {   
            case 0:
                x++;
                break;
            case 1:
                y++;
                break;
            case 2:
                x--;
                break;
            case 3:  
                y--;
                break;
        }

        if((++nc)==cnc)
        {   
            if(dmode == 3)
            {
                y++;
            }
            nc = 0;
            count--;
            dmode = ++dmode;
            if (dmode>3) {
                dmode%=4;
                x++;
            }
        }   
        
        if(!(count)) {
            count=4;
            cnc-=2;
        }   

    }   
    
    
    for(int y=0;y<n;y++){
        for(int x=0;x<n;x++)
            cout<<array[x][y]<<" ";
        cout<<endl;
    }   
}

int main()
{
    int i=0,k,j;
    cin>>k;
    
    for (; i<k; i++) {
        cin>>j;
        draw(j);
    }
}

